<?php
/**
 * Zhub - A PHP Framework For API Developer
 *
 * This file is part of the Zhub package.
 *
 * (c) YiLong Fan <fantiq@163.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author fanyilong <fantiq@163.com>
 * @copyright 2017 fanyilong. All rights reserved.
 * @package Zhub
 * @date 18-3-15
 */

namespace Zhub\Application\Http\Server;


use Zhub\DataStruct\Maps\StringMap;
use Zhub\HttpMessage\Headers\RequestHeader;
use Zhub\HttpMessage\Request;
use Zhub\HttpMessage\RequestMethod;
use Zhub\HttpMessage\Response;
use Zhub\Uri\Url\Url;
use Zhub\Uri\Url\UrlStruct;

class DefaultServer implements HttpServer
{
    public function getRequest():Request
    {
        list(, $protocolVersion) = explode('/', $_SERVER['SERVER_PROTOCOL']);
        return new Request([
            Request::METHOD => RequestMethod::id($_SERVER['REQUEST_METHOD']),
            Request::URL => $this->getUrl(),
            Request::PROTOCOL_VERSION => $protocolVersion,
            Request::HEADER => $this->getHeader(),
            Request::BODY => file_get_contents('php://input'),
        ]);
    }

    public function getHeader():RequestHeader
    {
        return new RequestHeader([
            RequestHeader::HEADER => new StringMap(getallheaders()),
            RequestHeader::COOKIE => new StringMap($_COOKIE),
        ]);
    }

    public function getUrl():UrlStruct
    {
        return Url::build([
            UrlStruct::SCHEME => 'http',
            UrlStruct::HOST => $_SERVER['HTTP_HOST'],
            UrlStruct::PORT => intval($_SERVER['SERVER_PORT']??0),
            UrlStruct::PATH => $_SERVER['REQUEST_URI']??'/',
            UrlStruct::QUERY => $_SERVER['QUERY_STRING']??''
        ]);
    }

    public function getServer(string $key = null, $def = null)
    {
        return $key == null ? $_SERVER :
            ($_SERVER[$key] ?? ($_SERVER[strtolower($key)]??null));
    }

    public function handleResponse(Response $response)
    {
        echo $response->getBody();
    }
}
